<template>
	<view class="callFask_container">
		<u-navbar title="确定用车" placeholder safeAreaInsetTop @leftClick="upOnelevel" :autoBack="true">
		</u-navbar>
		<!-- 地图 -->
		<view class="map_navigation">
			<!-- 标记点 ：  markers -->
			<map id="navMap" class="map" enable-traffic="true" show-location="true" :latitude="latitude"
				:longitude="longitude" :markers="initialPoint" :polyline="polyline">
			</map>
			<canvas canvas-id="effect" id="effect"></canvas>
		</view>
		<!-- 全程多少公里 -->
		<u-row customStyle="margin-bottom: 10px;margin-top: 10px;">
			<u-col span="12">
				<view class="tips">
					全程<text class="minuterText">{{kilometre}}km</text>,大约需要<text
						class="minuterText">{{minuter}}分钟</text>
				</view>
			</u-col>
		</u-row>
		<view class="money">
			预计<text class="red size-42">{{price}}</text>元
		</view>
		<view class="radio_user">
			<u-row gutter="10">
				<u-col span="1">
					<u-radio-group v-model="value" active-color="#00C28E">
						<u-radio name="1" :labelDisabled="false"></u-radio>
					</u-radio-group>
				</u-col>
				<u-col span="11">
					<view class="tipsView">
						遵守上述提示
						<text class="green" @click="goDetails('快车服务协议')">《快车服务协议》</text>
						<text class="green" @click="goDetails('计价规则')">《计价规则》</text>
					</view>
				</u-col>
			</u-row>
		</view>
		<view class="Thepeak">
			<u-popup :show="peakshow" mode="bottom" @close="closePopup">
				<view class="timeBox">
					<text class="tips">{{lineUp}}</text>
					<u-count-down @finish="endTime" :autoStart="false" ref="countDown" :time="time" @change="changeTime"
						format="HH:mm:ss">
					</u-count-down>
					<u-button :disabled="urgentBtnState" type="primary" @click="urgentBtn">加急叫车</u-button>
				</view>
			</u-popup>
		</view>
		<view class="call">
			<u-button type="primary" @click="callCar">开始叫车</u-button>
		</view>
		<!-- 取消模态框 -->
		<u-modal :show="isShow" showCancelButton @cancel="modalClose" @confirm="modalBtn" :title="title"
			:content='content'>
		</u-modal>
		<!-- 加急模态框 -->
		<u-modal :show="urgentshow" showCancelButton @cancel="urgentClose" @confirm="urgentEnsure" :title="title"
			:content='urgentcontent'>
		</u-modal>
		<!-- 提示订单的 -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import amap from "../../common/amap-wx.130.js"
	import {
		conversion
	} from '@/common/utils.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'

	import Particle from '@/common/effect.js'
	export default {
		data() {
			return {
				navMap: '', // 初始实例化地图对象
				amapPlugin: null, // 插件效果
				gaodeKey: "4412f1a1546136b8476c2c1011cbbad9", //  高德地图申请的key
				latitude: '', // 纬度
				longitude: '', // 经度
				Rain: null, //雨水--class
				with: 0, //宽
				height: 0, //高
				scale: 0, //屏幕宽度
				ctx: null, //控制雨水插件
				rain: null, //控制雨水的动画
				//  初始点(用户的初始位置)
				initialPoint: [],
				polyline: [], //路线的规划
				kilometre: '', // 路线多少公里
				minuter: '', //需要的时间
				price: 0, //预计金额
				value: '1', //单选框
				originLatLong: {}, //出发地的经纬度
				obj: {}, //订单的详细信息
				peakshow: false, //控制弹出层的倒计时
				isShow: false, //控制取消模态框的提示
				title: '提示', //模态框的标题
				content: '是否取消叫车？', //内容
				time: 60000, //高峰期倒计时进入叫车页面
				lineUp: '正在排队', //排队提示
				orderState: false, //订单状态
				repetitionTime: '', //重复发送给司机订单
				urgentshow: false, //加急功能模态框
				urgentcontent: '加急叫车，会使费用增加', //加急功能模态框内容
				urgentBtnState: false, //加急按钮的状态
				badWeather: false, //判断是否是恶劣天气
			}
		},
		onLoad(option) {
			this.kilometre = option.distance
			this.minuter = option.minute
			this.price = parseFloat(option.payMoney).toFixed(2)
			// 定位
			this.initialPoint = this.startEnd
			// 路线规划
			this.polyline = this.routePath
			// 出发地的经纬度---用户
			if (this.initPath) {
				this.originLatLong = {
					latitude: this.initPath.latitude,
					longitude: this.initPath.longitude
				}
				console.log(this.originLatLong, '---用户自己定位的', 129)
			}
			if (this.startPath) {
				this.originLatLong = {
					latitude: this.startPath.latitude,
					longitude: this.startPath.longitude
				}
				console.log(this.originLatLong, '--用户选择的地址', 136)
			}
			// 高德地图sdk的获取
			this.amapPlugin = new amap.AMapWX({
				key: this.gaodeKey
			})
			// 实例化地图对象
			this.navMap = uni.createMapContext("navMap", this)

			// this.getLocation()

			console.log(this.userSocketID, '用户ID', 146)

			// 缩放地图
			this.navMap.includePoints({
				padding: [90],
				points: this.theFinal
			})

			// 雨水效果
			this.Rain = Particle.Particle
			// 获取手机大小
			uni.getSystemInfo({
				success: res => {
					this.with = res.windowWidth
					this.scale = this.with / 375
				}
			})
			// 控制雨水动画
			this.ctx = uni.createCanvasContext('effect')
			this.height = 768 / 2 * this.scale
			this.rain = new this.Rain(this.ctx, this.with, this.height, {
				amount: 100,
				speedFactor: 0.03
			})
		},
		onShow() {
			// 接收socket的信息
			this.getmsg()
			if (this.weather == '大雨' || this.weather == '小雨' || this.weather == '中雨' || this
				.weather == '强降雨' || this
				.weather == '连续降雨') {
				// 开始下雨
				this.rain.run()
			} else {
				// 停止下雨
				this.rain.clear()
			}
		},
		computed: {
			...mapState('userLocation', ['initPath', 'startPath', 'endPath', 'startEnd', 'routePath', 'theFinal',
				'weather'
			]),
			...mapState('userInfo', ['userSocketID'])
		},
		methods: {
			...mapMutations('userInfo', ['setOrderInfo', 'setUserOrder']),
			...mapMutations('userLocation', ['getEnd']),
			// 收到司机接单信息
			getmsg() {
				this.socket.on('callUser', message => {
					console.log('收到服务器消息', message, 140)
					// 完整订单(用户、司机)
					this.setOrderInfo(message)

					// 关闭重复发送的订单--定时器
					clearInterval(this.repetitionTime)
					// 跳转
					this.orderState = true
					// 暂停时间
					this.$refs.countDown.pause()
				})
			},
			// // 获取用户当前位置
			// getLocation() {
			// 	uni.getLocation({
			// 		type: 'gcj02',
			// 		geocode: true,
			// 		success: res => {
			// 			this.latitude = res.latitude
			// 			this.longitude = res.longitude
			// 		},
			// 		fail(err) {
			// 			console.log(err, '报错了')
			// 		}
			// 	})
			// },
			// 叫车判断
			async callCar() {
				const result = await this.$http('/unfinishedOrder', {
					userID: this.userSocketID
				})
				if (result.userCallState == false) {
					this.$refs.uToast.show({
						type: 'error',
						message: result.message,
						iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png'
					})
					return
				}
				// 判断是否高峰期
				let time = conversion()
				// 早上开始
				let pmStime = time.nyr + ' ' + '07:00:00'
				pmStime = new Date(pmStime).getTime()
				// 早上结束
				let pmEtiem = time.nyr + ' ' + '09:00:00'
				pmEtiem = new Date(pmEtiem).getTime()
				// 晚上开始
				let amStime = time.nyr + ' ' + '17:00:00'
				amStime = new Date(amStime).getTime()
				// 晚上结束
				let amEtiem = time.nyr + ' ' + '19:00:00'
				amEtiem = new Date(amEtiem).getTime()
				// 当前时间戳
				let nowTime = new Date(time.nowTime).getTime()
				// 高峰期叫车---倒计时
				if (nowTime >= pmStime && nowTime <= pmEtiem || nowTime >= amStime && nowTime <= amEtiem) {
					// if (this.weather == '大雨' || this.weather == '小雨' || this.weather == '中雨' || this
					// 	.weather == '强降雨' || this
					// 	.weather == '连续降雨') {
					// 	console.log('当前处于高峰期叫车和恶劣天气叫车---提高价钱')
					// 	// 提高价钱
					// 	this.price = Number(this.price) + 10
					// }
					console.log('当前处于高峰期叫车')
					this.$refs.countDown.start()
					this.peakshow = true
					this.startCall()
				} else if (this.weather == '大雨' || this.weather == '小雨' || this.weather == '中雨' || this
					.weather == '强降雨' || this
					.weather == '连续降雨') {
					console.log('当前处于恶劣天气叫车')
					// 提高价钱
					// this.price = Number(this.price) + 10
					this.$refs.countDown.start()
					this.peakshow = true
					this.badWeather = true
					this.startCall()
				} else {
					console.log('正常情况叫车')
					this.startCall()
				}
			},
			// 开始叫车
			startCall() {
				let origin = ''
				let province = ''
				let city = ''
				let departure = ''
				// 自己定位地址
				if (this.initPath) {
					origin = this.initPath.name
					// province = this.initPath.province
					city = this.initPath.city
					departure = this.initPath.province + this.initPath.district
				}
				// 手动选择的地址
				if (this.startPath) {
					origin = this.startPath.name
					province = this.startPath.district.split('省')[0] + '省'
					city = this.startPath.city
					departure = this.startPath.address
				}
				console.log(city, '+++++++++++')
				this.obj = {
					// 出发地
					origin: origin,
					// 目的地
					bourn: this.endPath.name,
					// 省
					province: province,
					// 市
					city: city,
					//价格
					price: parseFloat(this.price).toFixed(2),
					// 目的地详细
					destination: this.endPath.district + this.endPath.name,
					// 出发地详细
					departure: departure,
					// 叫车类型
					carType: 27,
					// 路线
					route: JSON.stringify(this.theFinal),
					// 用户，出发地的经纬度
					originLatLong: JSON.stringify(this.originLatLong),
					//订单是否加急
					urgentState: false,
					// 是否恶劣天气
					badWeather: this.badWeather,
					// 叫车--用户
					socketID: this.userSocketID,
					// 订单状态---是否被接单
					state: 0,
					// 用户手机
					userPhone: uni.getStorageSync('userTable').userTel,
					// 用户名
					wxName: uni.getStorageSync('userTable').wxName,
					// 头像
					headPortrait: uni.getStorageSync('userTable').headPortrait,
					// 信誉分
					credit: uni.getStorageSync('userTable').credit,
				}
				// 当前时间戳
				let time = conversion()
				let nowTime = new Date(time.nowTime).getTime()
				this.obj.nowTime = nowTime

				// 发送请求
				this.$http('/userPlanOrder', this.obj, "POST").then(res => {
					if (res.code == 200) {
						// 订单号
						this.obj.ordernum = res.data.ordernum

						console.log(this.obj, '订单信息', 334)

						// 存入vuex---用户提交的订单（没有司机的经纬度）
						this.setUserOrder(this.obj)

						// 重复发送订单
						this.repetitionTime = setInterval(() => {
							// 发送 socket
							this.socket.emit('callCar', this.obj)
						}, 1000)

						// 排队--倒计时
						if (this.peakshow == false) {
							// 跳转暂停 此界面的定时器
							clearInterval(this.repetitionTime)
							uni.redirectTo({
								url: '/subpkg/callFaskwait/callFaskwait'
							})
						}
					} else {
						uni.$showMsg('叫车失败', 'error')
						return
					}
				})
			},
			// 倒计时变化
			changeTime() {
				if (this.lineUp.length == 7) {
					this.lineUp = '正在排队'
				} else if (this.lineUp.length <= 7) {
					this.lineUp += '.'
				}
			},
			// 关闭遮罩层
			closePopup() {
				console.log('关闭遮罩层')
				this.$refs.countDown.pause()
				this.isShow = true
			},
			// 倒计时结束触发
			endTime() {
				clearInterval(this.repetitionTime)
				this.peakshow = false
			},
			// 模态框确定取消叫车
			async modalBtn() {
				console.log(this.obj, '+++++++++++')
				clearInterval(this.repetitionTime)
				this.obj.cancelOrder = true
				// 更新订单状态
				const result = await this.$http('/userPlanOrder', this.obj, "POST")
				if (result.code == 200) {
					this.isShow = false
					this.$refs.uToast.show({
						type: 'success',
						message: result.data.message,
						iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png'
					})
					// 清空仓库的地址
					this.getEnd('')
					// 接单页面清除该用户订单--socket
					this.socket.emit('callCar', this.obj)

					uni.redirectTo({
						url: '/pages/home/home'
					})
				}
			},
			//  关闭模态框
			modalClose() {
				this.$refs.countDown.start()
				this.isShow = false
			},
			// 头部返回
			upOnelevel() {
				uni.navigateBack()
			},
			goDetails(title) {
				if (title == '快车服务协议') {
					uni.navigateTo({
						url: '/subpkg/serviceCar/serviceCar'
					})
				} else {
					uni.navigateTo({
						url: '/subpkg/valuationRules/valuationRules'
					})
				}
			},
			// 加急叫车功能
			urgentBtn() {
				this.$refs.countDown.pause()
				this.urgentshow = true
			},
			// 确定加急
			urgentEnsure() {
				clearInterval(this.repetitionTime)
				// 加钱
				this.obj.price = Number(this.obj.price) + 10
				// this.obj.price += 10
				// 订单状态
				this.obj.urgentState = true
				// 重新存入仓库
				this.setUserOrder(this.obj)
				// 重新发送订单
				this.repetitionTime = setInterval(() => {
					// 发送 socket
					this.socket.emit('callCar', this.obj)
				}, 1000)

				// 发送请求---修改价钱
				this.$http('/urgenOrder', this.obj, "POST").then(res => {
					if (res.code == 200) {
						uni.$showMsg(res.data.message, 'success')
					}
				})
				this.urgentshow = false
				this.urgentBtnState = true
				this.$refs.countDown.start()
			},
			// 关闭加急
			urgentClose() {
				this.$refs.countDown.start()
				this.urgentshow = false
			}
		},
		watch: {
			// 倒计时结束 跳转
			peakshow(newValue) {
				if (newValue == false) {
					uni.navigateTo({
						url: '/subpkg/callFaskwait/callFaskwait'
					})
				}
			},
			orderState(newValue) {
				if (newValue) {
					// 提示用户
					uni.showToast({
						title: '叫车成功',
						duration: 2000,
					})
					// 同步提示跳转
					setTimeout(() => {
						uni.navigateTo({
							url: '/subpkg/userWaitDriver/userWaitDriver'
						})
					}, 2000)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.map_navigation {
		position: relative;

		.map {
			height: 370px;
			width: 100%;
		}

		#effect {
			height: 400px;
			width: 100%;
			// border: 1px solid red;
			position: absolute;
			top: 0%;
		}
	}

	.tips {
		width: 100%;
		line-height: 100rpx;
		text-align: center;
		font-size: 35rpx;

		.minuterText {
			color: #FFAA4F;
		}
	}

	.money {
		line-height: 100rpx;
		font-size: 38rpx;
		text-align: center;
	}

	.radio_user {
		margin-top: 10rpx;
		display: flex;
		height: 100rpx;
		align-items: center;
		width: 100%;

		/deep/.u-radio {
			display: flex;
			flex-direction: row-reverse;
			margin-left: 10px !important;
		}

		.tipsView {
			width: 100%;
			font-size: 33rpx;
			line-height: 50rpx;
		}

		.green {
			color: #8CCFB2;
		}


	}

	.call {
		height: 96rpx;
		width: 100%;
		text-align: center;
		margin-top: 20rpx;
		padding-top: 10px;
	}

	.Thepeak {
		.timeBox {
			width: 100%;
			height: 220px;
			text-align: center;

			/deep/ .u-button--normal {
				font-size: 35rpx;
			}

			/deep/ .u-button--square {
				margin-top: 30px;
			}
		}

		/deep/ .u-count-down__text {
			font-size: 50rpx;
			line-height: 50px;
		}
	}

	/deep/ .u-modal__content__text {
		font-size: 20px;
		text-align: center;
	}
</style>
